package com.automannn.websocketmqtt.websocketNodeA.websocket;

import com.alibaba.fastjson.JSON;
import com.automannn.websocketmqtt.websocketNodeA.amqp.sender.WsMulticastSender;
import com.automannn.websoketmqtt.common.message.WsMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author chenkh
 * @time 2020/10/13 14:36
 */
@Component
@ServerEndpoint("/websoket/{name}")
public class AutomannnWebSocketService {

    @Autowired
    private WsMulticastSender wsMulticastSender;

    private static final Logger log = LoggerFactory.getLogger(AutomannnWebSocketService.class);

    private String name;

    private static ConcurrentHashMap<String, WebSocketSession> webSocketSet = new ConcurrentHashMap<>();

    @OnOpen
    public void onOpen(Session session, @PathParam(value = "name") String name){
        this.name = name;
        webSocketSet.put(name, (WebSocketSession) session);
        log.info("连接成功!当前连接:"+webSocketSet.keySet().toString());
    }

    @OnClose
    public void onClose(){
        webSocketSet.remove(this.name);
        log.info("退出成功,当前连接:"+webSocketSet.keySet().toString());
    }

    @OnMessage
    public void onMessage(String message){
        log.info("接收到消息:{}",message);
        WsMessage wsMessage = (WsMessage) JSON.parse(message);

        if (wsMessage!=null){
            wsMulticastSender.send(wsMessage);
        }
    }

    public void sendMessage(WsMessage wsMessage) throws IOException {
        if (wsMessage!=null){
            String receiver = wsMessage.getReceiver();
            //单播
            if (receiver!=null){
               WebSocketSession session= webSocketSet.get(receiver);
                TextMessage message = new TextMessage(JSON.toJSONString(wsMessage));
                session.sendMessage(message);
            }else{//组播
                webSocketSet.values().forEach(item->{
                    TextMessage message = new TextMessage(JSON.toJSONString(wsMessage));
                    try {
                        item.sendMessage(message);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                });
            }

        }
    }


}
